package com.loooooo.pm2024.security;

import com.loooooo.pm2024.utils.DigestUtils;
import com.loooooo.pm2024.utils.EncodeUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyPasswordEncoder implements PasswordEncoder {

    @Value("${app.security.key:cardshow05271020}")
    String key;

    @Value("${app.mode:}")
    String mode;

    @Override
    public String encode(CharSequence rawPassword) {
        byte[] salt = DigestUtils.generateSalt(32);
        return encode(rawPassword, salt);
    }

    public String encode(CharSequence rawPassword, byte[] salt) {

        String plain = rawPassword + key;
        //System.out.println(plain);
        byte[] hashPassword = DigestUtils.sha1(plain.getBytes(), salt, 1024);
        return EncodeUtils.encodeHex(salt) + EncodeUtils.encodeHex(hashPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        byte[] salt = EncodeUtils.decodeHex(encodedPassword.substring(0, 64));
        if ("init".equalsIgnoreCase(mode)) return true;
        return encode(rawPassword, salt).equalsIgnoreCase(encodedPassword);
    }
}
